<template>
  <div class="warehouse-type-manage">
    <el-card>
      <div slot="header" class="card-header">
        <span>仓库类型管理</span>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">
          新增类型
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" size="small">
        <el-form-item>
          <el-input
            v-model="queryForm.typeName"
            placeholder="类型名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="typeList" border stripe v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="typeName" label="类型名称" width="150" align="center" />
        <el-table-column label="类型图标" width="120" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.iconPath" :src="scope.row.iconPath" style="width: 50px; height: 50px; object-fit: contain;" />
            <i v-else class="el-icon-picture-outline" style="font-size: 32px; color: #ccc;"></i>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="类型描述" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleToggleStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              style="color: #F56C6C;"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型图标" prop="iconPath">
          <el-upload
            class="icon-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.iconPath" :src="form.iconPath" class="icon-preview" />
            <i v-else class="el-icon-plus icon-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议上传 100x100 像素的图片，支持 jpg、png 格式</div>
        </el-form-item>
        <el-form-item label="类型描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入类型描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import {
  getWarehouseTypeList,
  addWarehouseType,
  updateWarehouseType,
  deleteWarehouseType,
  updateWarehouseTypeStatus
} from '@/api/index/warehouseType';

export default {
  name: "WarehouseTypeManage",
  data() {
    return {
      loading: false,
      typeList: [],
      total: 0,
      queryForm: {
        typeName: '',
        pageNum: 1,
        pageSize: 20
      },
      dialogVisible: false,
      dialogType: 'add',
      submitLoading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      form: {
        id: null,
        typeName: '',
        iconPath: '',
        description: '',
        sortOrder: 0,
        status: '1'
      },
      rules: {
        typeName: [
          { required: true, message: '请输入类型名称', trigger: 'blur' }
        ],
        iconPath: [
          { required: true, message: '请上传类型图标', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return this.dialogType === 'add' ? '新增仓库类型' : '编辑仓库类型';
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取列表
    getList() {
      this.loading = true;
      getWarehouseTypeList(this.queryForm).then(res => {
        this.typeList = res.rows || res.data || [];
        this.total = res.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 查询
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },

    // 重置
    handleReset() {
      this.queryForm = {
        typeName: '',
        pageNum: 1,
        pageSize: 20
      };
      this.getList();
    },

    // 分页
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.queryForm.pageNum = val;
      this.getList();
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add';
      this.dialogVisible = true;
      this.form = {
        id: null,
        typeName: '',
        iconPath: '',
        description: '',
        sortOrder: 0,
        status: '1'
      };
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogVisible = true;
      this.form = { ...row };
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该仓库类型吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWarehouseType(row.id).then(() => {
          this.$message.success('删除成功');
          this.getList();
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },

    // 切换状态
    handleToggleStatus(row) {
      const action = row.status === '1' ? '启用' : '停用';
      updateWarehouseTypeStatus({ id: row.id, status: row.status }).then(() => {
        this.$message.success(`${action}成功`);
        this.getList();
      }).catch(() => {
        this.$message.error(`${action}失败`);
        // 失败时恢复原状态
        row.status = row.status === '1' ? '0' : '1';
      });
    },

    // 提交
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          const apiMethod = this.dialogType === 'add' ? addWarehouseType : updateWarehouseType;
          apiMethod(this.form).then(() => {
            this.$message.success('操作成功');
            this.dialogVisible = false;
            this.getList();
            this.submitLoading = false;
          }).catch(() => {
            this.$message.error('操作失败');
            this.submitLoading = false;
          });
        }
      });
    },

    // 关闭对话框
    handleDialogClose() {
      this.$refs.formRef.resetFields();
    },

    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    // 上传成功
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.form.iconPath = res.url;
        this.$message.success('上传成功');
      } else {
        this.$message.error(res.msg || '上传失败');
      }
    }
  }
};
</script>

<style scoped lang="scss">
.warehouse-type-manage {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .icon-uploader {
    ::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 100px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409EFF;
      }
    }

    .icon-preview {
      width: 100px;
      height: 100px;
      object-fit: contain;
    }

    .icon-uploader-icon {
      font-size: 28px;
      color: #8c939d;
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
  }
}
</style>
